package com.zeros.mysplash.http.callback;

import android.content.Context;
import android.content.Intent;

import com.zeros.mysplash.MyApplication;
import com.zeros.mysplash.UserCenter;
import com.zeros.mysplash.activity.LoginActivity;
import com.zeros.mysplash.bean.Common;
import com.zeros.mysplash.common.Constants;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/12/21.
 */

public abstract class CommonCallback<T extends Common> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.raw().code() == 200) {
            T body = response.body();
            if (body != null) {
                if (body.isValid()) {
                    if (body.getAttachment() != null) {
                        onSuccess(body.getAttachment());
                    } else {
                        onError("Attachment 对象为空");
                    }
                } else {
                    if (body.isNeedOut()) { //token过期重新登录
                        gotoLogInActivity();
                    } else if (body.isServiceBlock()) {

                    } else {
                        onError(body.getMessage());
                    }
                }
            } else {
                onError(response.message());
            }
        } else {
            onFailure(call, new RuntimeException("response error,detail = " + response.raw().toString()));
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (t instanceof SocketTimeoutException) {
            return;
        } else if (t instanceof ConnectException) {
            onError(t.getMessage());
        } else if (t instanceof RuntimeException) {
            onError(t.getMessage());
        } else {
            onError(t.getMessage());
        }
        call.cancel();
    }

    //token过期
    private void gotoLogInActivity() {
        Context context = MyApplication.getContext();
        UserCenter.getInstance().setToken(null);//清除token

        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(Constants.EXTRA_KEY_EXIT, true);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public abstract void onSuccess(Common.AttachmentBean attachmentBean);

    public void onError(String message) {

    }

}
